package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type Data struct {
	Name    string `json:"name"`
	Title   string `json:"title"`
	Address string `json:"address"`
	Port    int    `json:"port"`
	Model   int    `json:"model"`
}

type FuncDTO struct {
	Name  string `json:"name"`
	Input string `json:"input"`
}

type ResponseDTO struct {
	Output string `json:"output"`
}

const (
	LISTEM_PORT = 9990
	MODEL       = 1
	NAME        = "remove_space"
	TITLE       = "删除空格"
)

func main() {
	// 启动Web客户端
	go startWebClient()

	// 启动Web服务器
	startWebServer()
}

func base64Encode(str string) string {
	// 进行Base64编码
	return base64.StdEncoding.EncodeToString([]byte(str))
}

func base64Decode(str string) (string, error) {
	// 进行Base64解码
	decodedBytes, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		fmt.Println("Failed to decode string:", err)
		return "", err
	}

	return string(decodedBytes), nil
}

func startWebClient() {
	data := Data{
		Name:    NAME,
		Title:   base64Encode(TITLE),
		Address: "localhost",
		Port:    LISTEM_PORT,
		Model:   MODEL,
	}
	fmt.Printf("%v\n", data)

	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Failed to marshal JSON data:", err)
		return
	}

	resp, err := http.Post("http://localhost:8888/register", "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println("Failed to send POST request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Failed to read response body:", err)
		return
	}

	fmt.Println("Response:", string(body))
}

func replaceSpace(str string) string {
	// 删除头尾空格
	str = strings.TrimSpace(str)

	// 删除中间空格
	str = strings.ReplaceAll(str, " ", "")

	return str
}

func work(input string) (string, error) {
	return replaceSpace(input), nil
}

func startWebServer() {
	router := gin.Default()

	router.POST("/", func(c *gin.Context) {
		var data FuncDTO
		err := c.ShouldBindJSON(&data)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"code": 503, "message": err.Error(), "data": nil})
			return
		}

		fmt.Println("Received data:", data)

		input, err := base64Decode(data.Input)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"code": 503, "message": err.Error(), "data": nil})
			return
		}

		if result, err := work(input); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"code": 503, "message": err.Error(), "data": nil})
			return
		} else {
			out := ResponseDTO{Output: base64Encode(result)}
			c.JSON(http.StatusOK, gin.H{"code": 200, "message": "OK", "data": out})
			return
		}

	})

	host := fmt.Sprintf(":%d", LISTEM_PORT)
	fmt.Println("Listening on :", host)

	err := router.Run(host)
	if err != nil {
		fmt.Println("Failed to start web server:", err)
	}
}
